
<template>
    <!-- 人员弹框 -->
    <dialog-normal
    ref="dialog-staff"
    :dialog-prop="{
      title: title,
      height: '45vh',
      width: '60%',
      submit: '确定',
      close: '取消'
    }"
    @normal-submit="submitDialog('staff', currentItem)"
    >
    <template #dialog-content>
      <el-form
        class="form-content"
        ref="staff-form" label-position="left"
        :model="currentItem"
        label-width="100px">
          <div class="form-title">基本信息</div>
          <el-form-item class="form-content-item"
              label="人员姓名：" prop="nickName"
              :rules="{ required: true, message: `人员姓名不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['nickName']"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="登录账号：" prop="userName"
              :rules="[
                { required: true, message: `登录账号不能为空`, trigger: 'blur'},
                { validator: validatePhoneNum, trigger: 'blur'}
              ]">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['userName']"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="登录密码：" prop="password"
              :rules="{ required: true, message: `登录密码不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['password']" type="password"></el-input>
              </div>
              <!-- <el-button type="text" class="code-btn-unit" :loading="boo.isRandom" @click="randomPassword">随机密码</el-button> -->
          </el-form-item>
          <el-form-item class="form-content-item"
              label="状态：" prop="status"
              :rules="{ required: true, message: `账号状态不能为空`, trigger: 'blur'}">
            <div class="form-val no-border flex-normal">
              <el-radio-group v-model="currentItem.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <div class="form-title">权限信息</div>
          <div class="menu-content">
            <div class="menu-header flex-normal">
              <span class="header-item left-content">页面</span>
              <span class="header-item right-content">权限</span>
            </div>
            <div class="menu-main flex-normal">
              <div class="left-content">
                <div v-for="menu in menuList" :key="menu.id" 
                  :class="['item flex-normal', menu.isChecked && 'checked', currentMenu.id == menu.id && 'active']">
                  <span class="action-icon car-common-icon" @click="menuCheck(menu)">&#xe663;</span>
                  <span class="item-label menu-btn" @click="menuChange(menu)">{{menu.label}}</span>
                </div>
              </div>
              <div class="right-content">
                <div v-for="premi in premiList" :key="premi.id" @click="premiChange(premi)"
                  :class="['item flex-normal', premi.isChecked && 'checked']">
                  <span class="action-icon car-common-icon">&#xe663;</span>
                  <span class="item-label menu-btn">{{premi.label}}</span>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </template>
    </dialog-normal>
  </template>
  
  <script>
  import {
    addRole, editRole, 
    getRoleDetail, getMenuTree
  } from "@/api/userManage/admin-staff.js";
  import {randomPassword} from "@/api/userManage/admin-shop.js";
  import {isPhoneNum} from '@/utils/tools.js'
  export default {
    name: "List",
    props: {
       value: Object
    },
    components: {
      "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
    },
    data() {
      return {
        boo: {
          loading: false, // 遮罩层
          isRandom: false
        }, 
        title: '新增人员',
        currentItem: {
          menuIds: []
        },
        menuList: [],
        premiList: [],
        currentMenu: {}
      };
    },
    watch: {
      value: {
        handler: function (obj) {
          this.currentMenu = {}
          if(!obj) {
            return this.currentItem = {}
          }
          this.currentItem = obj
        },
        immediate: true
      }
    },
    methods: {
      validatePhoneNum: (rule, value, callback) => {
        if (!isPhoneNum(`${value}`)) {
          callback(new Error('请输入正确手机号'));
        } else {
          callback();
        }
      },
      menuChange(menu){
        let _self = this
        _self.premiList = menu.children || []
        _self.currentMenu = menu
      },
      menuCheck(menu){
        let _self = this
        _self.$set(menu, 'isChecked', !menu.isChecked)
        if(!menu.isChecked){
          menu.children.forEach(i => {
            _self.$set(i, 'isChecked', false)
          })
        }
      },
      premiChange(premi){
        let _self = this
        _self.$set(premi, 'isChecked', !premi.isChecked)
      },
      async randomPassword(){
        let _self = this
        _self.boo.isRandom = true
        await randomPassword().then(res => {
          _self.$set(_self.currentItem, 'password', res.msg)
        })
        _self.boo.isRandom = false
      },
      /** 查询用户列表 */
      queryMenuTree() {
        let _self = this
        return new Promise((resolve, reject) =>{
          getMenuTree().then((res) => {
            _self.menuList = res.data
            if(_self.menuList.length){
              _self.premiList = _self.menuList[0].children || []
            }
            resolve(true)
          })
        })
      },
      // 事件集合 -- 转发
      actionsMaps(ref, acion, row){
        let _self = this
        let actionsMap = () => {
          return new Map([
            [{ref: 'staff', acion: 'add:show'}, async ()=>{
              _self.title = '新增人员'
              _self.queryMenuTree().then(res => {
                _self.currentItem = {
                  menuIds: []
                }
                _self.$nextTick(() => {
                  _self.$refs[`dialog-${ref}`].showDialog = true
                })
              })
            }],
            [{ref: 'staff', acion: 'edit:show'}, async ()=>{
              _self.title = '编辑人员'
              _self.$set(row, 'isEdit', true)
              await _self.queryMenuTree()
              await getRoleDetail(row.userId).then(res => {
                _self.currentItem = res.data
                let {menuIds = []} = _self.currentItem
                _self.menuList.forEach(menu => {
                  _self.$set(menu, 'isChecked', menuIds.includes(menu.id))
                  menu.children = menu.children || []
                  menu.children.forEach(premi => {
                    _self.$set(premi, 'isChecked', menuIds.includes(premi.id))
                  })
                })
                _self.$nextTick(() => {
                  _self.$refs[`dialog-${ref}`].showDialog = true
                })
              })
              _self.$set(row, 'isEdit', false)
            }],
            [{ref: 'staff', acion: 'submit'}, async ()=>{
              let params = JSON.parse(JSON.stringify(row))
              let list = []
              _self.menuList.forEach(menu => {
                if(menu.isChecked){
                  list.push(menu.id)
                  menu.children = menu.children || []
                  let arr = menu.children.filter(i => i.isChecked).map(i => i.id)
                  list = [...list, ...arr]
                }
              })
              params['menuIds'] = list
              if(_self.currentItem.userId){
                await editRole(params).then(res => {
                  _self.$message.success('编辑成功')
                  _self.$nextTick(() => {
                    _self.$refs[`dialog-${ref}`].showDialog = false
                  })
                  _self.$emit('submit', 'edit')
                })
              }else {
                await addRole(params).then(res => {
                  _self.$message.success('添加成功')
                  _self.$nextTick(() => {
                    _self.$refs[`dialog-${ref}`].showDialog = false
                  })
                  _self.$emit('submit', 'add')
                })
              }
              _self.$refs[`dialog-${ref}`].loading = false
            }]
          ])
        }
        let actions = [...actionsMap()].filter(([key,value])=>(key.ref == ref && key.acion == acion))
        actions.forEach(([key,value])=>value.call(this))
      },
      showDialog(ref, type, row) {
        let _self = this;
        if (_self.$refs[`${ref}-form`]) {
          this.resetForm(`${ref}-form`);
        }
        _self.$nextTick(() => {
          _self.actionsMaps(ref, `${type}:show`, row)
        })
      },
      submitDialog(ref, row) {
        let _self = this;
        if(this.$refs[`${ref}-form`]){
          this.$refs[`${ref}-form`].validate((valid) => {
            if (valid) {
              _self.$refs[`dialog-${ref}`].loading = true
              _self.actionsMaps(ref, `submit`, row)
            } else {
              _self.$refs[`dialog-${ref}`].loading = false;
              return false;
            }
          });
        }else{
          _self.$refs[`dialog-${ref}`].loading = true
          _self.actionsMaps(ref, `submit`, row)
        }
      },
    }
  };
  </script>
  <style scoped lang="scss">
  .form-content{
    user-select: none;
    .form-content-item{
      position: relative;
      .code-btn-unit{
        position: absolute;
        left: vw(400);
        top: 50%;
        transform: translateY(-50%);
        font-size: vh(13);
        color: #0003AA;
        cursor: pointer;
      }
    }
    .form-title{
      margin-bottom: vh(20);
      line-height: vh(34);
      font-size: vh(13);
      color: #0003AA;
    }
    .form-val {
      width: vw(360);
      flex-wrap: nowrap;
      &.no-border{
        border: none;
      }
    }
  }
  .menu-content{
    line-height: normal;
    .left-content{
      width: 144px;
    }
    .right-content{
      flex: 1;
    }
    .menu-header{
      height: vh(34);
      background: rgba(237, 237, 237, 0.6);
      .header-item{
        font-size: vh(13);
        color: #3D3D3D;
      }
    }
    .menu-main{
      align-items: start;
      .menu-btn{
        margin-left: 15px;
      }
      .item{
        height: vh(42);
        font-size: vh(13);
        color: #3D3D3D;
        cursor: pointer;
        transition: .2s;
        padding: 0 15px;
        &:hover{
          background: #ECECEC;
        }
        &.checked{
          color: #0003AA;
        }
        &.active{          
          background: #ECECEC;
        }
        .action-icon{
          margin-right: 5px;
          font-weight: 600;
        }
      }
    }
  }
  </style>